package br.com.cfccultura.admin.control.actions.utils;

import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import br.com.cfccultura.admin.control.actions.DefaultAction;
import br.com.cfccultura.admin.control.forms.utils.CepForm;

@Component("/cep")
public class CepAction extends DefaultAction {
	
	private Logger logger = Logger.getLogger(CepAction.class);
	
	@Value("${cep.consulta.url}")
	private String url;
	
	public ActionForward consultaCep(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {		
		
		CepForm cepForm = (CepForm) form;
		
		logger.debug("Iniciando consulta pelo cep -> " + cepForm.getCep());
		
		URL url = new URL(getUrl() + cepForm.getCep());
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		logger.debug("Conectando...");
		conn.connect();
		logger.debug("Lendo bytes[]...");		
		String json = IOUtils.toString(conn.getInputStream());
		conn.disconnect();
		logger.debug("Disconectando...");
		
		PrintWriter out = response.getWriter();
		out.println(json.toString());
		
		return null;
	}
	
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}

}
